package xyz.xpman.prisonerfitness.entity;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Training {
    public static final String GUIDE = "guide";
    public static final String PART = "part";
    public static final String POINTS = "points";
    public static final String ACTIONS = "actions";
    public static final String STANDARD = "standard";

    private final Guide guide;
    private final String part;
    private final String points;
    private final TrainingStandard standard;
    private final List<TrainingAction> actions;

    public Training(Guide guide, String part, String points,
                    TrainingStandard standard,
                    List<TrainingAction> actions) {

        this.guide = guide;
        this.part = part;
        this.points = points;
        this.standard = standard;

        this.actions = (null == actions || actions.isEmpty())
                ? Collections.emptyList()
                : Collections.unmodifiableList(actions);
    }


    public String getPart() {
        return part;
    }

    public String getPoints() {
        return points;
    }

    public Guide getGuide() {
        return guide;
    }

    public List<TrainingAction> getActions() {
        return actions;
    }

    public TrainingStandard getStandard() {
        return standard;
    }



    public static Training byJson(@NotNull JSONObject json) {
        Training training = null;

        try {
            final Guide guide = Guide.byJson(json.getJSONObject(GUIDE));
            final String part = json.getString(PART);
            final String points = json.getString(POINTS);
            final TrainingStandard standard =
                    TrainingStandard.byJson(json.getJSONObject(STANDARD));


            List<TrainingAction> actions = Collections.emptyList();

            if (json.has(ACTIONS)) {
                final JSONArray array = json.getJSONArray(ACTIONS);
                actions = new ArrayList<>(array.length());

                for (int i = 0; i < array.length(); i++) {
                    actions.add(TrainingAction.byJson(array.getJSONObject(i)));
                }
            }

            training = new Training(guide, part, points, standard, actions);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return training;
    }

}
